Jx.declare('Jx.data.Table', {

	$extend: 'Jx.data.Collection',

	$requires: [

		'Jx.data.Index'

	],

	$actions: [

		'createRecord',

		'updateRecordIndex'

	],

	model: undefined,

	indexes: undefined,

	indexNames: undefined,

	name: undefined,

	constructor: function(model){

		if (Jx.isClass(model, 'Jx.data.Model')){

			this.model = model = Jx.getConstructor(model);

			this.indexes = {};

			this.indexNames = [];

			this.initializeModel( model );

		} else {

			throw Jx.createError('Invalid Model [', model , ']');

		}

		this.$super();

	},

	initializeModel: function(Model){

		this.name = Model.$name;

		//-- fields
		var fields = Model.getFields(),

			indexes = this.indexes,

			indexNames = this.indexNames;

		for(var index, name, indexClass, field, l = fields.length; l--;){

			field = fields.get(fields[l]);

			index = field.index();

			if (Jx.isClass(indexClass = 'data.index.'+index, 'Jx.data.Index')){

				name = field.name();

				indexNames[l] = name;

				indexes[ name ] = Jx.instantiate( indexClass, [

					this,

					field

				]);

			} else {

				indexNames.splice(l, 1);

			}

		}

	},

	onAfterItemsAdded: function( record, key, index ){

		var indexes = this.indexes,

			names = this.indexNames;

		//-- update index
		for(var l = names.length; l--;){

			record.objectId = key;

			indexes[ names[l] ].add(record);

		}

		this.$super(arguments);

	},

	onAfterItemRemoved: function( record, key, index ){

		var indexes = this.indexes,

			names = this.indexNames;

		//-- update index
		for(var l = names.length; l--;){

			indexes[ names[l] ].remove(record);

			delete record.objectId;

		}

		this.$super(arguments);

	}

});
